import datetime
import json

import settings
from social.account.models import User
from social.im.api import ZIMAPI
from social.utils.celery_app import app
from social.utils.jpush import JPush


@app.task()
def send_gift_message(gift_record_id):
    # 发送礼物消息
    from social.gift.models import GiftRecord
    gift_record = GiftRecord.objects.select_related('from_user', 'to_user', 'gift').get(id=gift_record_id)
    gift = gift_record.gift
    message = {
        'thumb': settings.IMAGE_HOST + gift.thumb,
        'title': f'送出{"搭讪" if gift.type == 3 else ""}礼物',
        'sub_title': f'{gift.name}x{gift_record.count}',
        'desc': '相逢便是缘，认识一下吧~' if gift.type == 3 else ''
    }
    ZIMAPI().send_custom_message(from_user_id=gift_record.from_user.im_id, to_user_id=gift_record.to_user.im_id,
                                 sub_msg_type=1, message=str(json.dumps(message)))

    # 推送
    if gift.coin >= 500:
        date = datetime.datetime.now() - datetime.timedelta(minutes=5)
        us = User.objects.filter(last_active__gte=date)[:100]
        ids = [x.hid for x in us]
        if len(ids):
            extra = {
                'avatar': gift_record.from_user.avatar.url,
                'gift_icon': gift.thumb,
                'from': gift_record.from_user.nickname,
                'to': gift_record.to_user.nickname,
                'gift_name': gift.name,
                'count': gift_record.count
            }
            JPush.send_push(ids, None, None, content_type='gift', extra=extra)
